﻿using System.ComponentModel.Composition;
using System.Windows;
using System.Windows.Controls;
using MediaAssistant.Controls.WaitScreen;
using MefBasic;
using MefBasic.Threading;
using MediaAssistant.DAL;

namespace MediaAssistant.Controls.MovieThumbnails
{
    [Export]
    public partial class MovieThumbnailsView : IView
    {
        public MovieThumbnailsView()
        {
            InitializeComponent();
        }

private void HandleScrollChanged(object sender, ScrollChangedEventArgs e)
{
    ShowVisibleItems(sender);
}

private void ShowVisibleItems(object sender)
{
    var scrollViewer = (FrameworkElement) sender;
    var visibleAreaEntered = false;
    var visibleAreaLeft = false;
    var invisibleItemDisplayed = 0;
    foreach (Movie item in thumbnailListBox.Items)
    {
        if (item.IsVisible) continue;
        var listBoxItem = (FrameworkElement) thumbnailListBox.ItemContainerGenerator.ContainerFromItem(item);
        if (visibleAreaLeft==false && IsFullyOrPartiallyVisible(listBoxItem, scrollViewer))
        {
            visibleAreaEntered = true;
        }
        else if (visibleAreaEntered)
        {
            visibleAreaLeft = true;
        }
        if(visibleAreaEntered)
        {
            if(visibleAreaLeft && ++invisibleItemDisplayed>10)
                break;
            var job = new Job(MakeVisible);
            job.Store.Add(item);
            job.Start();
        }
    }
}

private static void MakeVisible(Job obj)
{
    obj.Store.GetObject<Movie>().IsVisible = true;
}

protected bool IsFullyOrPartiallyVisible(FrameworkElement child, FrameworkElement scrollViewer)
{
    var childTransform = child.TransformToAncestor(scrollViewer);
    var childRectangle = childTransform.TransformBounds(new Rect(new Point(0, 0), child.RenderSize));
    var ownerRectangle = new Rect(new Point(0, 0), scrollViewer.RenderSize);
    return ownerRectangle.IntersectsWith(childRectangle);
}

    }
}